package com.example.springbootmvc.controller;

import com.example.springbootmvc.model.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    private static String _SESSION_KEY = "SESSION_KEY";

    @RequestMapping("/add")
    public User add(User user) {
        return user;
    }

    @RequestMapping("/name")
    public String name(@RequestParam(value = "n",required = false) String name) {
        return name;
    }

    /**
     * 获取前端的json对象
     * @param user
     * @return
     */
    @RequestMapping("/add_json")
    public User addByJson(@RequestBody User user) {
        return user;

    }

    @RequestMapping("/detail/{aid}")
    public Integer detail(@PathVariable("aid") Integer aid) {
        return aid;
    }

    @RequestMapping("/detail2/{aid}/{name}")
    public String detail2(@PathVariable("aid") Integer aid,@PathVariable String name) {
        return "aid:" + aid + " name:" + name;
    }

    //上传文件
    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
        //1.生成一个唯一的id  UUID :全球唯一ID-> MAC+随机种子+加密算法
        String name = UUID.randomUUID().toString().replace("-","");

        //2.得到源文件的后缀名
        name += (file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));

        //
        String path = "E:\\Logging\\" + name;
        //保存文件
        file.transferTo(new File(path));
        return path;
    }


    //获取cookie
    @RequestMapping("/getcookie")
    public String getCookie(@CookieValue(value = "java",required = false) String ck) {
        return ck;
    }

    @RequestMapping("/set_sess")
    public String doPostConstruct(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute(_SESSION_KEY,"zhangsan");
            return "session set ok";
        } else {
            return "session set fail";
        }
    }

    /**
     * 获取session
     * @param name
     * @return
     */
    @RequestMapping("/get_sess")
    public String getSess(@SessionAttribute(required = false,value = "SESSION_KEY") String name) {
        return name;
    }
}
